package com.example.j202411.views.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.j202411.R;
import com.example.j202411.adapter.HourlyWeatherAdapter;
import com.google.gson.Gson;

import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Unit;
import com.qweather.sdk.bean.weather.WeatherHourlyBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.HeConfig;
import com.qweather.sdk.view.QWeather;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class Weather extends AppCompatActivity {

    private TextView tv_tianqi;
    private TextView tv_wendu;
    private TextView tv_fengxiang;
    private TextView tv_fengli, tv_fengsu, tv_humidity, city_name01, btn_future;
    private ImageButton btn_search_city;
    private TextView tv_date_time; // 新增的 TextView 引用

    private RecyclerView recyclerView;
    private HourlyWeatherAdapter adapter;























    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);

        tv_tianqi = findViewById(R.id.textView1);
        tv_wendu = findViewById(R.id.textView4);
        tv_fengxiang = findViewById(R.id.textView5);
        tv_fengli = findViewById(R.id.textView3);
        tv_fengsu = findViewById(R.id.textView10);
        tv_humidity = findViewById(R.id.textView13);
        btn_search_city = findViewById(R.id.btn_search_city);
        city_name01 = findViewById(R.id.city_name01);
        tv_date_time = findViewById(R.id.textView2); // 绑定新的 TextView
        btn_future = findViewById(R.id.textView16);
        HeConfig.init("TMWDXF9A9A", "9317fc0e6392490db5340fe380d09ed3");
        HeConfig.switchToDevService();

        // 默认查询某个城市的天气
        queryWeather("CN101070201");

        btn_search_city.setOnClickListener(v -> {
            Intent intent = new Intent(Weather.this, SearchCityActivity.class);
            startActivityForResult(intent, 1);
        });

        btn_future.setOnClickListener(v -> {
            Intent intent = new Intent(Weather.this, WeatherFuture.class);
            startActivityForResult(intent, 1);
        });

        // 设置当前日期和时间
        updateDateTime();

        recyclerView = findViewById(R.id.recyclerView11);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setHasFixedSize(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            if (data != null) {
                String cityId = data.getStringExtra("cityId");
                String cityName = data.getStringExtra("cityName");
                city_name01.setText(cityName); // 设置城市名称
                queryWeather(cityId);
            }
        }
    }

    public void queryWeather(String cityId) {
        QWeather.getWeatherNow(this, cityId, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherNowListener() {
            public static final String TAG = "he_feng_now";

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: ", e);
                System.out.println("Weather Now Error: " + e.getMessage());
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                System.out.println("获取天气成功： " + new Gson().toJson(weatherBean));
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                    String tianqi = now.getText();
                    String wendu = now.getTemp() + "℃";
                    String fengli = now.getWindScale();
                    String fengxiang = now.getWindDir();
                    String fengsu = now.getWindSpeed();
                    String humidity = now.getHumidity();

                    tv_tianqi.setText(tianqi);
                    tv_wendu.setText(wendu);
                    tv_fengxiang.setText("风向：" + fengxiang);
                    tv_fengli.setText("风力：" + fengli + "级");
                    tv_fengsu.setText(fengsu + "Km/h");
                    tv_humidity.setText(humidity + "%");
                } else {
                    // 在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    System.out.println("失败代码: " + code);
                }
            }
        });

        // 调用QWeather SDK获取24小时天气预报数据
        QWeather.getWeather24Hourly(this, cityId, Lang.ZH_HANS, Unit.METRIC, new QWeather.OnResultWeatherHourlyListener() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Log.e("Weather", "获取24小时天气数据时发生错误: " + e.getMessage());
            }

            @Override
            public void onSuccess(WeatherHourlyBean result) {
                Log.d("Weather", "24小时天气数据获取成功");

                if (result != null && result.getHourly() != null) {
                    final List<WeatherHourlyBean.HourlyBean> hourlyDataList = result.getHourly();
                    Log.d("Weather", "小时数据点数量: " + hourlyDataList.size());

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter = new HourlyWeatherAdapter(hourlyDataList, Weather.this);
                            recyclerView.setAdapter(adapter);
                            Log.d("Weather", "适配器已设置到RecyclerView");
                        }
                    });
                } else {
                    Log.w("Weather", "结果中没有小时数据");
                }
            }
        });
    }

    private void updateDateTime() {
        // 获取当前日期和时间
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("M 月 d 日 | h:mma", Locale.CHINA);
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置时区为北京时间
        String formattedDateTime = dateFormat.format(calendar.getTime());

        // 更新 TextView
        tv_date_time.setText(formattedDateTime);
    }
}